/// 弹出菜单
/// 1.可以通过controller控制菜单的弹出
/// 2.该组件返回的是Sizebox(),是个空的内容,外部可以通过Row或Coloumn的方式与任意
/// widget组合,实现弹出菜单功能
/// 3.菜单项menuItems由外部传入
/// 4.选择了某项菜单后,通过外部实现的onSelected方法进行处理

import 'package:flutter/material.dart';


class WFPopupMenu<T> extends StatefulWidget {

  WFPopupMenuController? controller;
  Color? backgroundColor;
  double? elevation;
  final PopupMenuItemSelected<T>? onSelected;
  List<PopupMenuEntry<T>> menuItems;

  WFPopupMenu(this.menuItems,{Key? key, this.controller,this.backgroundColor=Colors.white,this.elevation=8.0,this.onSelected}) : super(key: key);

  @override
  _WFPopupMenuState createState() => _WFPopupMenuState();
}


class _WFPopupMenuState<T> extends State<WFPopupMenu> {
  final _popupButtonKey = GlobalKey<State>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.controller?._showMenu=(){
      print('needshowmenu');
      _doShowmenu();
    };
  }

   @override
   Widget build(BuildContext context) {
    return _buildPopmenu();
   }

  _buildPopmenu() {
    return PopupMenuButton<T>(
      key: _popupButtonKey,
      color: widget.backgroundColor!,
      onSelected: widget.onSelected,
      itemBuilder: (context) {
        return [
          ...widget.menuItems.cast()
        ];
      },

      child: SizedBox(),
    );
  }

   _doShowmenu() {
     // Here we get the render object of our physical button, later to get its size & position
     final RenderObject? popupButtonObject1 = _popupButtonKey.currentContext?.findRenderObject();
     final RenderBox popupButtonObject = popupButtonObject1! as RenderBox;

     // Get the render object of the overlay used in `Navigator` / `MaterialApp`, i.e. screen size reference
     final RenderObject? overlay1 = Overlay.of(context).context.findRenderObject();
     final RenderBox overlay = overlay1! as RenderBox;

     // Calculate the show-up area for the dropdown using button's size & position based on the `overlay` used as the coordinate space.
     final RelativeRect position = RelativeRect.fromRect(
       Rect.fromPoints(
         popupButtonObject.localToGlobal(Offset.zero, ancestor: overlay),
         popupButtonObject.localToGlobal(popupButtonObject.size.bottomRight(Offset.zero), ancestor: overlay),
       ),
       Offset.zero & overlay.size, // same as: new Rect.fromLTWH(0.0, 0.0, overlay.size.width, overlay.size.height)
     );

     // Finally, show the menu.
     showMenu(
       context: context,
       elevation: widget.elevation, // default value
       color: widget.backgroundColor!,
       items: widget.menuItems,
       initialValue: null,
       position: position,
     ).then((res) {
       if (widget.onSelected!=null) {
         widget.onSelected!(res);
       }
     });
   }

   _doHideMenu(){

   }
}

///**********************************
class WFPopupMenuController {
  Function? _showMenu;
  showMenu() {
    _showMenu?.call();
  }
}
